package demo;

import java.lang.reflect.Constructor;

public enum TestEnum {
    RED("red",1),BLACK("black",2),WHITE("white",3),GREEN("green",4);
    private String name;
    private int key;

    /**
     *
     * @param name
     * @param key
     */

    private TestEnum (String name,int key) {
        this.name = name;
        this.key = key;
    }


    public static TestEnum getEnumKey (int key) {
        for (TestEnum t: TestEnum.values()) {
            if(t.key == key) {
                return t;
            }
        }
        return null;
    }

    public static void reflectPrivateConstructor() {
        try {
            Class<?> classStudent = Class.forName("demo.TestEnum");
            //注意传入对应的参数,获得对应的构造方法来构造对象,当前枚举类是提供了两个参数分别是String和int。
            Constructor<?> declaredConstructorStudent = classStudent.getDeclaredConstructor(String.class,int.class,String.class,int.class);
            //设置为true后可修改访问权限
            declaredConstructorStudent.setAccessible(true);
            //后两个为子类参数，大家可以将当前枚举类的key类型改为double验证
            Object objectStudent = declaredConstructorStudent.newInstance("父类参数",666,"子类参数",888);
            TestEnum testEnum = (TestEnum) objectStudent;
            System.out.println("获得枚举的私有构造函数："+testEnum);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        reflectPrivateConstructor();
    }

    /*RED,BLACK,GREEN,WHITE;

    public static void main(String[] args) {
        TestEnum[] testEnum = TestEnum.values();
        for (int i = 0; i < testEnum.length; i++) {
            System.out.println(testEnum[i] + " " + testEnum[i].ordinal());
        }
        System.out.println("=========================");
        System.out.println(TestEnum.valueOf("GREEN"));
    }

    public static void main1(String[] args) {
        TestEnum testEnum2 = TestEnum.BLACK;
        switch (testEnum2) {
            case RED:
                System.out.println("red");
                break;
            case BLACK:
                System.out.println("black");
                break;
            case WHITE:
                System.out.println("WHITE");
                break;
            case GREEN:
                System.out.println("black");
                break;
            default:
                break;
        }
    }*/
}
